package org.company.ci.servlets;

import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.company.ci.domain.Pedido;
import org.company.ci.pdf.PedidoPdfCreator;
import org.company.ci.services.PedidoService;
import org.company.ci.services.ServiceFinder;

/**
 * Servlet implementation class GenerarPdfServlet
 */
public class GenerarPdfServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private ServletConfig config;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GenerarPdfServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Servlet#init(ServletConfig)
	 */
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String idPedido = request.getParameter("id_pedido");
		
		PedidoService pedidoService =(PedidoService) ServiceFinder.getBean(config.getServletContext(),"pedidoService");
		try {
			Pedido pedidoBD = pedidoService.getPedidoById(new Long(idPedido));
			
			PedidoPdfCreator creator = new PedidoPdfCreator(pedidoBD);
			
			byte [] bytesPdf = creator.createPdf();
			
			response.setContentType("application/pdf");

			response.setContentLength(bytesPdf.length);
			
			ServletOutputStream ouputStream = response.getOutputStream();

			//la siguiente linea, te obliga a descargar y le da el nombre//
			response.addHeader("content-disposition","attachment; filename=pedido_"+idPedido+".pdf");
			ouputStream.write(bytesPdf, 0, bytesPdf.length);
			ouputStream.flush();
			ouputStream.close();
			
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
